/**
 * 麦克风SDK UI组件模块
 * 提供基本的UI组件和DOM操作接口
 */

import MicrophoneSDK from '../MicrophoneSDK.js';

/**
 * 创建麦克风按钮
 * @param {string} containerId - 容器元素ID
 * @param {Object} options - 配置选项
 * @returns {HTMLElement} 按钮元素
 */
export function createMicrophoneButton(containerId, options = {}) {
  const container = document.getElementById(containerId);
  if (!container) {
    console.error('未找到容器元素:', containerId);
    return null;
  }
  
  // 默认选项
  const defaultOptions = {
    startText: 'Start Microphone',
    stopText: 'Stop Microphone',
    className: 'microphone-button',
    autoStart: false
  };
  
  // 合并选项
  const settings = { ...defaultOptions, ...options };
  
  // 创建按钮
  const button = document.createElement('button');
  button.textContent = settings.startText;
  button.className = settings.className;
  
  // 状态变量
  let isListening = false;
  
  // 更新按钮状态
  const updateButtonState = (listening) => {
    isListening = listening;
    button.textContent = isListening ? settings.stopText : settings.startText;
    button.classList.toggle('active', isListening);
  };
  
  // 点击事件处理
  button.addEventListener('click', async () => {
    if (isListening) {
      await MicrophoneSDK.stopListening();
    } else {
      await MicrophoneSDK.startListening();
    }
  });
  
  // 监听状态变化
  const unsubscribe = MicrophoneSDK.onMicrophoneStatusChange(status => {
    updateButtonState(status.isListening);
  });
  
  // 添加到容器
  container.appendChild(button);
  
  // 如果设置了自动启动
  if (settings.autoStart) {
    setTimeout(() => {
      MicrophoneSDK.startListening();
    }, 500);
  }
  
  // 返回按钮元素和清理函数
  button.dispose = () => {
    unsubscribe();
    button.removeEventListener('click', button.clickHandler);
    if (button.parentNode) {
      button.parentNode.removeChild(button);
    }
  };
  
  return button;
}

/**
 * 创建音频电平指示器
 * @param {string} containerId - 容器元素ID
 * @param {Object} options - 配置选项
 * @returns {HTMLElement} 指示器元素
 */
export function createAudioLevelMeter(containerId, options = {}) {
  const container = document.getElementById(containerId);
  if (!container) {
    console.error('未找到容器元素:', containerId);
    return null;
  }
  
  // 默认选项
  const defaultOptions = {
    width: '100%',
    height: '20px',
    backgroundColor: '#eee',
    foregroundColor: '#4CAF50',
    showValue: false,
    className: 'audio-level-meter'
  };
  
  // 合并选项
  const settings = { ...defaultOptions, ...options };
  
  // 创建容器
  const meterContainer = document.createElement('div');
  meterContainer.className = settings.className;
  meterContainer.style.width = settings.width;
  meterContainer.style.height = settings.height;
  meterContainer.style.backgroundColor = settings.backgroundColor;
  meterContainer.style.position = 'relative';
  meterContainer.style.overflow = 'hidden';
  meterContainer.style.borderRadius = '3px';
  
  // 创建电平指示
  const levelBar = document.createElement('div');
  levelBar.style.height = '100%';
  levelBar.style.width = '0%';
  levelBar.style.backgroundColor = settings.foregroundColor;
  levelBar.style.transition = 'width 0.1s ease-out';
  meterContainer.appendChild(levelBar);
  
  // 如果显示数值
  let valueDisplay = null;
  if (settings.showValue) {
    valueDisplay = document.createElement('div');
    valueDisplay.style.position = 'absolute';
    valueDisplay.style.top = '0';
    valueDisplay.style.left = '0';
    valueDisplay.style.width = '100%';
    valueDisplay.style.height = '100%';
    valueDisplay.style.display = 'flex';
    valueDisplay.style.alignItems = 'center';
    valueDisplay.style.justifyContent = 'center';
    valueDisplay.style.color = '#000';
    valueDisplay.style.fontWeight = 'bold';
    valueDisplay.style.textShadow = '0 0 2px #fff';
    valueDisplay.textContent = '0%';
    meterContainer.appendChild(valueDisplay);
  }
  
  // 更新电平
  const updateLevel = (level) => {
    const percentage = Math.round(level * 100);
    levelBar.style.width = `${percentage}%`;
    
    if (valueDisplay) {
      valueDisplay.textContent = `${percentage}%`;
    }
  };
  
  // 监听音频电平变化
  const unsubscribe = MicrophoneSDK.onAudioLevelChange(updateLevel);
  
  // 添加到容器
  container.appendChild(meterContainer);
  
  // 返回元素和清理函数
  meterContainer.dispose = () => {
    unsubscribe();
    if (meterContainer.parentNode) {
      meterContainer.parentNode.removeChild(meterContainer);
    }
  };
  
  return meterContainer;
}

/**
 * 创建麦克风设备选择器
 * @param {string} containerId - 容器元素ID
 * @param {Object} options - 配置选项
 * @returns {HTMLElement} 选择器元素
 */
export function createMicrophoneSelector(containerId, options = {}) {
  const container = document.getElementById(containerId);
  if (!container) {
    console.error('未找到容器元素:', containerId);
    return null;
  }
  
  // 默认选项
  const defaultOptions = {
    label: 'Select Microphone:',
    className: 'microphone-selector',
    refreshButtonText: 'Refresh',
    showRefreshButton: true
  };
  
  // 合并选项
  const settings = { ...defaultOptions, ...options };
  
  // 创建容器
  const selectorContainer = document.createElement('div');
  selectorContainer.className = settings.className;
  selectorContainer.style.display = 'flex';
  selectorContainer.style.alignItems = 'center';
  selectorContainer.style.gap = '10px';
  
  // 创建标签
  if (settings.label) {
    const label = document.createElement('label');
    label.textContent = settings.label;
    selectorContainer.appendChild(label);
  }
  
  // 创建选择器
  const select = document.createElement('select');
  select.style.flexGrow = '1';
  selectorContainer.appendChild(select);
  
  // 创建刷新按钮
  let refreshButton = null;
  if (settings.showRefreshButton) {
    refreshButton = document.createElement('button');
    refreshButton.textContent = settings.refreshButtonText;
    refreshButton.addEventListener('click', async () => {
      await MicrophoneSDK.refreshMicrophoneList();
    });
    selectorContainer.appendChild(refreshButton);
  }
  
  // 更新麦克风列表
  const updateMicrophoneList = async () => {
    // 清空选择器
    select.innerHTML = '';
    
    // 获取麦克风列表
    const microphones = MicrophoneSDK.getAvailableMicrophones();
    
    // 如果没有麦克风，添加一个禁用的选项
    if (microphones.length === 0) {
      const option = document.createElement('option');
      option.textContent = 'No microphones found';
      option.disabled = true;
      select.appendChild(option);
      return;
    }
    
    // 添加麦克风选项
    microphones.forEach(mic => {
      const option = document.createElement('option');
      option.value = mic.deviceId;
      option.textContent = mic.label || `Microphone (${mic.deviceId.substr(0, 5)}...)`;
      select.appendChild(option);
      
      // 如果是当前选择的麦克风，选中它
      const status = MicrophoneSDK.getMicrophoneStatus();
      if (status.selectedMicrophone && status.selectedMicrophone.deviceId === mic.deviceId) {
        option.selected = true;
      }
    });
  };
  
  // 选择变化事件
  select.addEventListener('change', async () => {
    const deviceId = select.value;
    if (deviceId) {
      await MicrophoneSDK.selectMicrophone(deviceId);
    }
  });
  
  // 监听麦克风列表变化
  const unsubscribe = MicrophoneSDK.onMicrophoneListChange(() => {
    updateMicrophoneList();
  });
  
  // 初始化麦克风列表
  updateMicrophoneList();
  
  // 添加到容器
  container.appendChild(selectorContainer);
  
  // 返回元素和清理函数
  selectorContainer.dispose = () => {
    unsubscribe();
    if (refreshButton) {
      refreshButton.removeEventListener('click', refreshButton.clickHandler);
    }
    select.removeEventListener('change', select.changeHandler);
    if (selectorContainer.parentNode) {
      selectorContainer.parentNode.removeChild(selectorContainer);
    }
  };
  
  return selectorContainer;
}

/**
 * 创建增益控制滑块
 * @param {string} containerId - 容器元素ID
 * @param {Object} options - 配置选项
 * @returns {HTMLElement} 滑块元素
 */
export function createGainSlider(containerId, options = {}) {
  const container = document.getElementById(containerId);
  if (!container) {
    console.error('未找到容器元素:', containerId);
    return null;
  }
  
  // 默认选项
  const defaultOptions = {
    label: 'Microphone Gain:',
    min: 0,
    max: 2,
    step: 0.1,
    defaultValue: 1,
    className: 'gain-slider',
    showValue: true
  };
  
  // 合并选项
  const settings = { ...defaultOptions, ...options };
  
  // 创建容器
  const sliderContainer = document.createElement('div');
  sliderContainer.className = settings.className;
  sliderContainer.style.display = 'flex';
  sliderContainer.style.alignItems = 'center';
  sliderContainer.style.gap = '10px';
  
  // 创建标签
  if (settings.label) {
    const label = document.createElement('label');
    label.textContent = settings.label;
    sliderContainer.appendChild(label);
  }
  
  // 创建滑块
  const slider = document.createElement('input');
  slider.type = 'range';
  slider.min = settings.min;
  slider.max = settings.max;
  slider.step = settings.step;
  slider.value = settings.defaultValue;
  slider.style.flexGrow = '1';
  sliderContainer.appendChild(slider);
  
  // 创建值显示
  let valueDisplay = null;
  if (settings.showValue) {
    valueDisplay = document.createElement('span');
    valueDisplay.textContent = settings.defaultValue;
    valueDisplay.style.minWidth = '2em';
    valueDisplay.style.textAlign = 'right';
    sliderContainer.appendChild(valueDisplay);
  }
  
  // 滑块变化事件
  slider.addEventListener('input', () => {
    const value = parseFloat(slider.value);
    MicrophoneSDK.setGain(value);
    
    if (valueDisplay) {
      valueDisplay.textContent = value.toFixed(1);
    }
  });
  
  // 添加到容器
  container.appendChild(sliderContainer);
  
  // 返回元素和清理函数
  sliderContainer.dispose = () => {
    slider.removeEventListener('input', slider.inputHandler);
    if (sliderContainer.parentNode) {
      sliderContainer.parentNode.removeChild(sliderContainer);
    }
  };
  
  return sliderContainer;
}

/**
 * 创建状态指示器
 * @param {string} containerId - 容器元素ID
 * @param {Object} options - 配置选项
 * @returns {HTMLElement} 状态指示器元素
 */
export function createStatusIndicator(containerId, options = {}) {
  const container = document.getElementById(containerId);
  if (!container) {
    console.error('未找到容器元素:', containerId);
    return null;
  }
  
  // 默认选项
  const defaultOptions = {
    className: 'status-indicator',
    listeningText: 'Microphone is active',
    notListeningText: 'Microphone is inactive',
    permissionGrantedText: 'Permission granted',
    permissionDeniedText: 'Permission denied',
    permissionUnknownText: 'Permission unknown'
  };
  
  // 合并选项
  const settings = { ...defaultOptions, ...options };
  
  // 创建容器
  const statusContainer = document.createElement('div');
  statusContainer.className = settings.className;
  statusContainer.style.display = 'flex';
  statusContainer.style.flexDirection = 'column';
  statusContainer.style.gap = '5px';
  
  // 创建监听状态指示器
  const listeningStatus = document.createElement('div');
  listeningStatus.style.display = 'flex';
  listeningStatus.style.alignItems = 'center';
  listeningStatus.style.gap = '5px';
  
  const listeningIndicator = document.createElement('span');
  listeningIndicator.style.width = '10px';
  listeningIndicator.style.height = '10px';
  listeningIndicator.style.borderRadius = '50%';
  listeningIndicator.style.backgroundColor = '#ccc';
  
  const listeningText = document.createElement('span');
  listeningText.textContent = settings.notListeningText;
  
  listeningStatus.appendChild(listeningIndicator);
  listeningStatus.appendChild(listeningText);
  statusContainer.appendChild(listeningStatus);
  
  // 创建权限状态指示器
  const permissionStatus = document.createElement('div');
  permissionStatus.style.display = 'flex';
  permissionStatus.style.alignItems = 'center';
  permissionStatus.style.gap = '5px';
  
  const permissionIndicator = document.createElement('span');
  permissionIndicator.style.width = '10px';
  permissionIndicator.style.height = '10px';
  permissionIndicator.style.borderRadius = '50%';
  permissionIndicator.style.backgroundColor = '#ccc';
  
  const permissionText = document.createElement('span');
  permissionText.textContent = settings.permissionUnknownText;
  
  permissionStatus.appendChild(permissionIndicator);
  permissionStatus.appendChild(permissionText);
  statusContainer.appendChild(permissionStatus);
  
  // 更新状态
  const updateStatus = (status) => {
    // 更新监听状态
    if (status.isListening) {
      listeningIndicator.style.backgroundColor = '#4CAF50';
      listeningText.textContent = settings.listeningText;
    } else {
      listeningIndicator.style.backgroundColor = '#ccc';
      listeningText.textContent = settings.notListeningText;
    }
    
    // 更新权限状态
    if (status.hasPermission === true) {
      permissionIndicator.style.backgroundColor = '#4CAF50';
      permissionText.textContent = settings.permissionGrantedText;
    } else if (status.hasPermission === false) {
      permissionIndicator.style.backgroundColor = '#F44336';
      permissionText.textContent = settings.permissionDeniedText;
    } else {
      permissionIndicator.style.backgroundColor = '#ccc';
      permissionText.textContent = settings.permissionUnknownText;
    }
  };
  
  // 监听状态变化
  const unsubscribe = MicrophoneSDK.onMicrophoneStatusChange(updateStatus);
  
  // 初始化状态
  updateStatus(MicrophoneSDK.getMicrophoneStatus());
  
  // 添加到容器
  container.appendChild(statusContainer);
  
  // 返回元素和清理函数
  statusContainer.dispose = () => {
    unsubscribe();
    if (statusContainer.parentNode) {
      statusContainer.parentNode.removeChild(statusContainer);
    }
  };
  
  return statusContainer;
}

/**
 * 创建完整的麦克风控制面板
 * @param {string} containerId - 容器元素ID
 * @param {Object} options - 配置选项
 * @returns {HTMLElement} 控制面板元素
 */
export function createMicrophoneControlPanel(containerId, options = {}) {
  const container = document.getElementById(containerId);
  if (!container) {
    console.error('未找到容器元素:', containerId);
    return null;
  }
  
  // 默认选项
  const defaultOptions = {
    title: 'Microphone Control',
    className: 'microphone-control-panel',
    showTitle: true,
    showButton: true,
    showMeter: true,
    showSelector: true,
    showGainSlider: true,
    showStatus: true
  };
  
  // 合并选项
  const settings = { ...defaultOptions, ...options };
  
  // 创建面板容器
  const panel = document.createElement('div');
  panel.className = settings.className;
  panel.style.display = 'flex';
  panel.style.flexDirection = 'column';
  panel.style.gap = '15px';
  panel.style.padding = '15px';
  panel.style.border = '1px solid #ccc';
  panel.style.borderRadius = '5px';
  panel.style.backgroundColor = '#f9f9f9';
  
  // 创建标题
  if (settings.showTitle && settings.title) {
    const title = document.createElement('h3');
    title.textContent = settings.title;
    title.style.margin = '0 0 10px 0';
    panel.appendChild(title);
  }
  
  // 创建组件容器
  const components = {};
  
  // 创建麦克风按钮
  if (settings.showButton) {
    const buttonContainer = document.createElement('div');
    panel.appendChild(buttonContainer);
    components.button = createMicrophoneButton(buttonContainer.id, options.buttonOptions);
  }
  
  // 创建音频电平指示器
  if (settings.showMeter) {
    const meterContainer = document.createElement('div');
    panel.appendChild(meterContainer);
    components.meter = createAudioLevelMeter(meterContainer.id, options.meterOptions);
  }
  
  // 创建麦克风选择器
  if (settings.showSelector) {
    const selectorContainer = document.createElement('div');
    panel.appendChild(selectorContainer);
    components.selector = createMicrophoneSelector(selectorContainer.id, options.selectorOptions);
  }
  
  // 创建增益滑块
  if (settings.showGainSlider) {
    const sliderContainer = document.createElement('div');
    panel.appendChild(sliderContainer);
    components.gainSlider = createGainSlider(sliderContainer.id, options.sliderOptions);
  }
  
  // 创建状态指示器
  if (settings.showStatus) {
    const statusContainer = document.createElement('div');
    panel.appendChild(statusContainer);
    components.status = createStatusIndicator(statusContainer.id, options.statusOptions);
  }
  
  // 添加到容器
  container.appendChild(panel);
  
  // 返回面板和清理函数
  panel.components = components;
  panel.dispose = () => {
    // 清理所有组件
    Object.values(components).forEach(component => {
      if (component && typeof component.dispose === 'function') {
        component.dispose();
      }
    });
    
    // 移除面板
    if (panel.parentNode) {
      panel.parentNode.removeChild(panel);
    }
  };
  
  return panel;
}

// 导出组件
export default {
  createMicrophoneButton,
  createAudioLevelMeter,
  createMicrophoneSelector,
  createGainSlider,
  createStatusIndicator,
  createMicrophoneControlPanel
}; 